<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2019/08/05 14:55
 * Desc: 游记
 */
class Controller_Pc_Api_Standard_Travelnotes extends Controller_Pc_Api_Base
{
    private $_typeid = 101;   //产品类型

    public function before()
    {
        parent::before();
    }

    /**
     * @desc 获取轮播图
     */
    public function action_get_index_banner()
    {
        $result = DB::select()->from('xcx_ads')->where('prefix','=','s_notes_index')
            ->order_by('displayorder','asc')->execute()->as_array();
        foreach($result as &$v){
            //判断产品类型
            if($v['typeid'] == 101){
                $v['url'] = '../details/details';
                $mod = DB::select('litpic','memberid')->from('notes');
            }
            if(!empty($mod)){
                $row = $mod ->where('id','=',$v['proid'])->execute()->current();
                //增加图片绝对访问地址
                $v['litpic'] = Common::img($row['litpic']);
                // 作者名称
                $nickname  = DB::select("nickname")->from("member")->where("mid","=",$row['memberid'])->execute()->get('nickname');
                $v['name'] = $nickname ? $nickname : '';
            }
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }


    /**
     * 获取首页游记列表
     * @function
     */
    public function action_get_notes_list()
    {

        $page_size = intval($this->request_body->content->pagesize);//条数
        $page      = intval($this->request_body->content->page); //页码
        $keyword   = $this->request_body->content->keyword;
        $mid       = intval($this->request_body->content->mid); // 会员id
        $path      = $this->request_body->content->path; // 其他搜索条件
        $params = array(
            'page' => $page,
            'pagesize' => $page_size,
            'keyword'  => $keyword,
            'mid' => $mid
        );

        if($path)
        {
            list($params['destpy'], $params['dayid'], $params['priceid'], $params['sorttype'], , $params['startcityid'], $params['attrid'], $params['page']) = explode('-', $path);
        }

        $out = Model_Api_Standard_Travelnotes::search($params);
        foreach($out['list'] as &$v){
            $v['url'] = '../details/details';
            if(!$mid)
            {
                $favorite_m = false;
            }
            else
            {
                $hash_key = md5($mid . 'note_id=' . $v['id']);
                $favorite_m = Model_Api_Standard_Travelnotes::favorite_log($hash_key);
            }

            $v['favorite_m'] = $favorite_m;
            $v['userImg'] = empty($v['userImg']) ? "/res/images/member_nopic.png" : $v['userImg'];
            $v['userImg'] = Model_Api_Standard_System::reorganized_resource_url($v['userImg']);
        }

        $result = array(
            'total' => $out['row_count'],
            'data' => $out['list'],
            'row_count' => $out['row_count'],
            'status' => $out['status']
        );

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 获取游记详情
     * @function
     */
    public function action_get_notes_detail()
    {
        // 游记id
        $productid = intval($this->request_body->content->productid);
        // 会员id
        $memberid = intval($this->request_body->content->memberid);

        $params = array(
            'id' => $productid
        );
        $info  = Model_Api_Standard_Travelnotes::detail($params);
        if(empty($info) || ($info['status']!=1 && $info['memberid']!=$memberid))
        {
            $result = array();
        }
        else
        {
            // 会员信息
            $memberInfo = Model_Member::get_member_byid($info['memberid']);
            $info['memberinfo'] = $memberInfo;
            if($info['memberinfo'])
            {
                $info['memberinfo']['litpic'] = empty($info['memberinfo']['litpic']) ? Common::nopic() :  $info['memberinfo']['litpic'];
                $info['memberinfo']['litpic'] = Model_Api_Standard_System::reorganized_resource_url($info['memberinfo']['litpic']);
            }
            // 点评数量
            $info['commentnum'] = Model_Comment::get_comment_num($info['id'],$this->_typeid);
            // 阅读数量+1
            DB::update('notes')->set(array('shownum'=> ($info['shownum']+ 1)))->where('id',"=",$info['id'])->execute();
            // 前台显示虚拟阅读量+真实阅读量
            $info['shownum'] += $info['read_num'];
            $info['favorite']+= $info['virtual_favorite'];
            // 处理内容里面的图片地址
            $info['content'] = Model_Api_Standard_Travelnotes::add_http_html($info['content'],'src="');
            // 点赞提示
            if(!$memberid)
            {
                $favorite_m = false;
            }
            else
            {
                $hash_key   = md5($memberid . 'note_id=' . $info['id']);
                $favorite_m = Model_Api_Standard_Travelnotes::favorite_log($hash_key);
            }
            $info['favorite_m'] = $favorite_m;
            $result = array(
                'data' => $info
            );
        }

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 游记点赞
     * @function
     */
    public function action_add_focus()
    {
        $notes_id = intval($this->request_body->content->notesid);
        $memberid = intval($this->request_body->content->memberid);

        $hash_key = md5($memberid . 'note_id=' . $notes_id);
        $favorite = Model_Api_Standard_Travelnotes::favorite_log($hash_key);
        if ($favorite) {
            $result = array('status'=> 'hased','msg'=> '每篇游记只能点赞1次');
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            exit();
        }
        $value_arr = array('favorite' => DB::expr('favorite + 1'));
        $isupdated = DB::update('notes')->set($value_arr)->where('id', '=', $notes_id)->execute();

        if($isupdated)
        {
            Model_Api_Standard_Travelnotes::favorite_log($hash_key,'add');
            $result = array('status' => 'success', 'msg' => '点赞成功');
        }
        else
        {
            $result = array('status' => 'error', 'msg' => '点赞失败');
        }

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }


    /**
     * 获取游记评论列表
     * @function
     */
    public function action_get_comment_list()
    {
        $pagesize = intval($this->request_body->content->pagesize); //条数
        $page = intval($this->request_body->content->page);//页码
        $id = intval($this->request_body->content->productid);  // 产品id

        // 获取评论列表
        $result = Model_Comment::search_result($this->_typeid,$id,'',$page,$pagesize);

        // 处理封面图片
        foreach ($result['list'] as &$v)
        {
            $v['litpic'] = empty($v['litpic']) ? Common::nopic() : $v['litpic'];
            $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($v['litpic']);
        }

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 发布评论
     * @function
     * @throws Kohana_Exception
     */
    public function action_save_comment()
    {

        // 产品id
        $id = intval($this->request_body->content->productid);
        $dockid = intval($this->request_body->content->dockid);

        $mid = intval($this->request_body->content->memberid);
        // 匿名
        $ops = intval($this->request_body->content->op);
        $mid = $ops ? 0 : $mid;
        // 评论内容
        $comment = Common::remove_xss($this->request_body->content->comment);

        if(strlen($comment) < 5)
        {
            $result = array('status' => 101,'msg' => '请至少输入5个字');
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }

        //游记是否开启审核
        $isshow = 0;
        if ($GLOBALS['cfg_notes_pinlun_audit_open']==='0')
        {
            $isshow = 1;
        }

        // 需要保存的数据
        $data = array(
            'articleid'=> $id,
            'content'  => $comment,
            'typeid'   => $this->_typeid,
            'memberid' => $mid,
            'dockid' => $dockid,
            'isshow' => $isshow,
            'addtime'=> time(),
        );

        // 保存数据
        list($noteid,$row) = DB::insert('comment',array_keys($data))->values(array_values($data))->execute();
        if($row)
        {
            $msg = '发布成功，审核中';
            // 如果是直接显示 直接进行审核
            if($isshow == 1)
            {
                $msg = '发布成功';
                Model_Comment::on_verified($noteid,$this->_typeid,$mid);
            }
            // 获取最新一条数据
            $result = Model_Comment::search_result($this->_typeid,$id,'',1,1);
            // 处理封面图片
            foreach ($result['list'] as &$v)
            {
                $v['litpic'] = empty($v['litpic']) ? Common::nopic() : $v['litpic'];
                $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($v['litpic']);
            }
            $result['status'] = 200;
            $result['msg'] = $msg;
        }
        else
        {
            $result = array('status' => 102,'msg' => '提交评论失败');
        }

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

    }

    /**
     * 保存游记图片
     * @function
     */
    public function action_save_notes_image()
    {
        $img_base = $this->request_body->content->imgpath;
        $path = '/uploads/notes/'.date('Ymd').'/';
        $imgs = $this->base64_image_content($img_base,$path);
        if($imgs)
        {
            $imgs = Common::img($imgs);
        }
        $result = array('data'=> $imgs);
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 保存游记
     * @function
     */
    public function action_save_notes()
    {
        $mid     = intval($this->request_body->content->mid);
        $noteid  = intval($this->request_body->content->noteid);
        $content = $this->request_body->content->content;
        $content = preg_replace("/<p.*?>|<\/p>/is","", $content);
        $title   = Common::remove_xss($this->request_body->content->title);
        $addimgurl = Common::remove_xss($this->request_body->content->addimgurl);

        if(!$mid)
        {
            $result = array("status"=> 100,"msg"=> "请先登录");
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }

        $data = array(
            'title'    => $title,
            'memberid' => $mid,
            'litpic'   => $addimgurl,
            'bannerpic'=> '/res/images/notes_default_banner.png',
            'modtime'  => time(),
            'content'  => $content
        );

        if(!$noteid)
        { // 添加
            $data["addtime"] = time();
            list($noteid,$row) = DB::insert("notes",array_keys($data))->values(array_values($data))->execute();
            $result = array("status"=> 101,"msg"=> "发布游记失败！");
            if($row)
            {
                // 添加游记消息
                Model_Message::add_note_msg(100,$noteid,"");
                $result = array("status"=> 200,"msg"=> "你的游记已提交，正在等待管理员审核你可在个人中心查看审核状态");
            }

        }
        else
        { // 编辑
            // 查询编辑数据
            $info = DB::select()->from("notes")->where("id","=",$noteid)->and_where("memberid","=",$mid)->execute()->current();
            if(!$info)
            {
                $result = array("status"=> 102,"msg"=> "操作异常");
            }
            else
            {
                $res = DB::update("notes")->set($data)->where("id","=",$noteid)->execute();
                $result = array("status"=> 200,"msg"=> "编辑游记成功！");
            }
        }

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 保存base64位图片
     * @function
     * @param $base64_image_content
     * @param $path
     * @return bool|string
     */
    public function base64_image_content($base64_image_content,$path)
    {
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $new_file =  dirname(dirname(dirname(dirname(dirname(dirname(dirname(__DIR__))))))).$path;
            if(!file_exists($new_file)){
                //检查是否有该文件夹，如果没有就创建
                mkdir($new_file, 0777);
            }
            $img = time().rand(1000,9999).".{$type}";
            $new_file = $new_file.$img;
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                return $path.$img;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }


    /**
     * 获取我的游记
     * @function
     */
    public function action_get_my_notes()
    {
        $pagesize = intval($this->request_body->content->pagesize); //条数
        $page = intval($this->request_body->content->page);//页码
        $mid  = intval($this->request_body->content->mid);// 会员id
        $page = empty($page)?1:$page;
        $offset = $pagesize*($page-1);
        $list=Model_Notes::search(null,null,'1',false,$offset,$pagesize,$mid);
        foreach($list as &$row)
        {
            $memberInfo = Model_Member::get_member_byid($row['memberid']);
            $row['modtime'] = date('Y-m-d',$row['modtime']);
            $row['memberinfo'] = $memberInfo;
        }

        $this->send_datagrams($this->client_info['id'], $list, $this->client_info['secret_key']);
    }

    /**
     * 删除游记
     * @function
     */
    public function action_delete_my_note()
    {
        $id  = intval($this->request_body->content->deleteid);//页码
        $mid = intval($this->request_body->content->mid);// 会员id

        if(!$id)
        {
            $result = array('status' => 101, 'msg' => '操作异常');
        }
        else
        {
            $info = DB::select()->from("notes")->where("id","=",$id)->execute()->current();
            if(!$info)
            {
                $result = array('status' => 102, 'msg' => '删除的内容不存在');
            }
            else
            {
                if($info['memberid']!=$mid)
                {
                    $result = array('status' => 103, 'msg' => '请勿操作不属于您的内容');
                }
                else
                {
                    DB::delete("notes")->where("id","=",$id)->execute();
                    $result = array('status' => 200, 'msg' => '删除成功');
                }
            }
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
}